/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007-2008 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.projects.toolbox_basics_project.web.gwt.form.bean.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.transaction.annotation.Transactional;

import com.genia.toolbox.basics.exception.BundledException;
import com.genia.toolbox.basics.exception.technical.TechnicalException;
import com.genia.toolbox.persistence.bean.CrossSessionObject;
import com.genia.toolbox.persistence.manager.PersistenceManager;
import com.genia.toolbox.projects.toolbox_basics_project.bean.PersistableApplicationParameter;
import com.genia.toolbox.projects.toolbox_basics_project.bean.model.I18nDynamicText;
import com.genia.toolbox.projects.toolbox_basics_project.bean.model.I18nStringParameter;
import com.genia.toolbox.projects.toolbox_basics_project.bean.model.Parameter;
import com.genia.toolbox.projects.toolbox_basics_project.bean.model.impl.I18nStringParameterImpl;
import com.genia.toolbox.projects.toolbox_basics_project.spring.manager.CommonFormManager;
import com.genia.toolbox.projects.toolbox_basics_project.spring.manager.ParameterManager;
import com.genia.toolbox.projects.toolbox_basics_project.web.gwt.form.bean.FormParameterHandler;
import com.genia.toolbox.web.gwt.basics.client.oracle.SimpleSuggestion;
import com.genia.toolbox.web.gwt.form.client.form.MutableItem;
import com.genia.toolbox.web.gwt.form.client.form.impl.I18nTextAreaItemImpl;
import com.genia.toolbox.web.gwt.form.client.value.FormSimpleValue;
import com.genia.toolbox.web.gwt.form.client.value.impl.FormSimpleValueImpl;

/**
 * Implementation of {@link FormParameterHandler} for {@link I18nDynamicText}.
 */
public class I18nStringFormParameterHandler
    implements FormParameterHandler<I18nDynamicText>
{

  /**
   * {@link CommonFormManager}.
   */
  private CommonFormManager commonFormManager;

  /**
   * the {@link ParameterManager} to use.
   */
  private ParameterManager parameterManager;

  /**
   * the {@link PersistenceManager} to use.
   */
  private PersistenceManager persistenceManager;



  /**
   * returns the current value of the parameter given in argument.
   * 
   * @param applicationParameter
   *          the parameter to extract the current value from
   * @return the current value of the parameter given in argument
   * @see com.genia.toolbox.projects.toolbox_basics_project.web.gwt.form.bean.FormParameterHandler#getCurrentValue(com.genia.toolbox.projects.toolbox_basics_project.bean.PersistableApplicationParameter)
   */
  public FormSimpleValue getCurrentValue(PersistableApplicationParameter<I18nDynamicText> applicationParameter)
  {
    FormSimpleValueImpl formSimpleValue = new FormSimpleValueImpl();
    formSimpleValue.setName(applicationParameter.getReferenceName());
    formSimpleValue.setValues(applicationParameter.getValue() == null ? null : getCommonFormManager().createStringList(applicationParameter.getValue()));
    return formSimpleValue;
  }



  /**
   * returns the {@link MutableItem} that allow editing of the current
   * parameter.
   * 
   * @param label
   *          the label of this parameter.
   * @param applicationParameter
   *          the parameter to generate the from
   * @return the {@link MutableItem} that allow editing of the current parameter
   * @see com.genia.toolbox.projects.toolbox_basics_project.web.gwt.form.bean.FormParameterHandler#getForm(com.genia.toolbox.projects.toolbox_basics_project.bean.PersistableApplicationParameter,
   *      String)
   */
  public MutableItem getItem(String label, PersistableApplicationParameter<I18nDynamicText> applicationParameter)
  {
    return new I18nTextAreaItemImpl();
  }



  /**
   * set the current value of the parameter given in argument.
   * 
   * @param applicationParameter
   *          the parameter to set the current value from
   * @param formSimpleValue
   *          the new value of the parameter
   * @throws TechnicalException
   *           if an error occured
   * @see com.genia.toolbox.projects.toolbox_basics_project.web.gwt.form.bean.FormParameterHandler#setCurrentValue(com.genia.toolbox.projects.toolbox_basics_project.bean.PersistableApplicationParameter,
   *      com.genia.toolbox.web.gwt.form.client.value.FormSimpleValue)
   */
  @SuppressWarnings("unchecked")
  @Transactional(rollbackFor = TechnicalException.class)
  public void setCurrentValue(PersistableApplicationParameter<I18nDynamicText> applicationParameter, FormSimpleValue formSimpleValue)
      throws TechnicalException
  {
    I18nDynamicText value = applicationParameter.getValue();
    if (value == null || value.getIdentifier() == null) {
      value = getCommonFormManager().createI18nDynamicText(formSimpleValue.getValues());
      applicationParameter.setValue(getPersistenceManager().getCrossSessionManager().getCrossSessionObject(value));
      Parameter parameter = getParameterManager().getParameter(applicationParameter.getReferenceName());
      if (parameter != null && (!(parameter instanceof I18nStringParameter))) {
        getParameterManager().delete(parameter);
        parameter = null;
      }
      if (parameter == null) {
        parameter = new I18nStringParameterImpl();
        parameter.setReferenceName(applicationParameter.getReferenceName());
        getParameterManager().save(parameter);
      }
      I18nStringParameter i18nStringParameter = (I18nStringParameter) parameter;
      if (i18nStringParameter.getI18nValue() != null) {
        I18nDynamicText oldValue = i18nStringParameter.getI18nValue();
        getCommonFormManager().delete(oldValue);
      }
      i18nStringParameter.setI18nValue(value);
      getParameterManager().update(i18nStringParameter);
    }
    else {
      value = (I18nDynamicText) ((CrossSessionObject) applicationParameter.getValue()).getCurrentObject();
      getCommonFormManager().updateI18nDynamicText(value, formSimpleValue.getValues());
    }

  }



  /**
   * getter for the commonFormManager property.
   * 
   * @return the commonFormManager
   */
  public CommonFormManager getCommonFormManager()
  {
    return commonFormManager;
  }



  /**
   * setter for the commonFormManager property.
   * 
   * @param commonFormManager
   *          the commonFormManager to set
   */
  public void setCommonFormManager(CommonFormManager commonFormManager)
  {
    this.commonFormManager = commonFormManager;
  }



  /**
   * returns the {@link Set} of {@link Class} that this handler handle.
   * 
   * @return the {@link Set} of {@link Class} that this handler handle or
   *         <code>null</code> if this handler is the default one
   * @see com.genia.toolbox.projects.toolbox_basics_project.bean.ParameterHandler#getHandlingClasses()
   */
  @SuppressWarnings("unchecked")
  public Set<Class<? extends I18nDynamicText>> getHandlingClasses()
  {
    return new HashSet<Class<? extends I18nDynamicText>>(Arrays.asList(I18nDynamicText.class));
  }



  /**
   * getter for the parameterManager property.
   * 
   * @return the parameterManager
   */
  public ParameterManager getParameterManager()
  {
    return parameterManager;
  }



  /**
   * setter for the parameterManager property.
   * 
   * @param parameterManager
   *          the parameterManager to set
   */
  public void setParameterManager(ParameterManager parameterManager)
  {
    this.parameterManager = parameterManager;
  }



  /**
   * getter for the persistenceManager property.
   * 
   * @return the persistenceManager
   */
  public PersistenceManager getPersistenceManager()
  {
    return persistenceManager;
  }



  /**
   * setter for the persistenceManager property.
   * 
   * @param persistenceManager
   *          the persistenceManager to set
   */
  public void setPersistenceManager(PersistenceManager persistenceManager)
  {
    this.persistenceManager = persistenceManager;
  }



  /**
   * get the display string for a given value.
   * 
   * @param applicationParameter
   *          the parameter to get the suggestions for
   * @param value
   *          the current value of the field
   * @return the string to display for the given value
   * @throws BundledException
   *           when an error occurred
   * @see com.genia.toolbox.projects.toolbox_basics_project.web.gwt.form.bean.FormParameterHandler#getDisplayString(com.genia.toolbox.projects.toolbox_basics_project.bean.PersistableApplicationParameter,
   *      java.lang.String)
   */
  public String getDisplayString(PersistableApplicationParameter<I18nDynamicText> applicationParameter, String value)
      throws BundledException
  {
    // Should never be called.
    assert (false);
    return null;
  }



  /**
   * get suggestions for the parameter given in argument.
   * 
   * @param applicationParameter
   *          the parameter to get the suggestions for
   * @param query
   *          the current value of the field
   * @param limit
   *          the maximum number of response
   * @return the list of suggestion for the field
   * @throws BundledException
   *           when an error occurred
   * @see com.genia.toolbox.projects.toolbox_basics_project.web.gwt.form.bean.FormParameterHandler#getSuggestions(com.genia.toolbox.projects.toolbox_basics_project.bean.PersistableApplicationParameter,
   *      java.lang.String, int)
   */
  public List<SimpleSuggestion> getSuggestions(PersistableApplicationParameter<I18nDynamicText> applicationParameter, String query, int limit)
      throws BundledException
  {
    // Should never be called.
    assert (false);
    return null;
  }

}
